package com.intelligent.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.pojo.Workshops;
import com.intelligent.service.WorkshopsService;
import com.intelligent.mapper.WorkshopsMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.apache.ibatis.annotations.Param;

/**
* @author lenovo
* @description 针对表【workshops(车间信息表)】的数据库操作Service实现
* @createDate 2025-08-30 14:48:49
*/
@Service
public class WorkshopsServiceImpl extends ServiceImpl<WorkshopsMapper, Workshops>
    implements WorkshopsService{

    @Override
    public IPage<Workshops> getWorkshopsPage(Page<Workshops> page, 
                                            String workshopCode,
                                            String workshopName,
                                            String username,
                                            Integer status) {
        return baseMapper.selectWorkshopsPage(page, workshopCode, workshopName, username, status);
    }

    @Override
    public Workshops getWorkshopsById(Long id) {
        return baseMapper.selectWorkshopsById(id);
    }

    @Override
    public boolean addWorkshop(Workshops workshops) {
        // 自动生成车间编号
        workshops.setWorkshopCode(generateWorkshopCode());
        // 设置默认状态为启用
        if (workshops.getStatus() == null) {
            workshops.setStatus(0);
        }
        return save(workshops);
    }

    @Override
    public String generateWorkshopCode() {
        String maxCode = baseMapper.selectMaxWorkshopCode();
        if (maxCode == null || maxCode.isEmpty()) {
            // 如果没有现有编号，从WS001开始
            return "WS001";
        }
        
        // 提取数字部分
        String numStr = maxCode.substring(2);
        int num = Integer.parseInt(numStr);
        // 生成下一个编号
        return String.format("WS%03d", num + 1);
    }

    @Override
    public boolean updateWorkshop(Workshops workshops) {
        // 验证车间信息是否存在
        if (workshops.getId() == null) {
            throw new IllegalArgumentException("车间ID不能为空");
        }
        
        // 验证车间编号是否重复（排除当前记录）
        Workshops existingWorkshop = getById(workshops.getId());
        if (existingWorkshop == null) {
            throw new IllegalArgumentException("车间信息不存在");
        }
        
        // 执行更新操作
        return updateById(workshops);
    }

    @Override
    public boolean deleteWorkshopById(Long id) {
        // 验证车间信息是否存在
        if (id == null) {
            throw new IllegalArgumentException("车间ID不能为空");
        }
        
        Workshops existingWorkshop = getById(id);
        if (existingWorkshop == null) {
            throw new IllegalArgumentException("车间信息不存在");
        }
        
        // 执行删除操作
        return removeById(id);
    }
}




